package com.adpython.service.impl;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.adpython.service.SeoService;
import com.google.appengine.repackaged.org.apache.commons.logging.Log;
import com.google.appengine.repackaged.org.apache.commons.logging.LogFactory;

public class SeoServiceImpl implements SeoService {
	
	protected  Log log = LogFactory.getLog(getClass());
	
	private static Map<String,Map> seoRuleCache;
	
	public Map parseSeoRule(String url){
		if(seoRuleCache==null){
			this.cacheSeoRuleMap();
		}
		return seoRuleCache.get(url);
	}
	
	private void cacheSeoRuleMap(){
		URL path=this.getClass().getClassLoader().getResource("com/python/resources/seo-mapping.xml");
		try{
			SAXReader reader = new SAXReader();
			Document document = reader.read(path);
			Element root = document.getRootElement();
			List<Element> nodeslist=root.elements();
			Map<String,Map> seoMap=new HashMap<String,Map>();
			for(Element node:nodeslist){
				Map itemMap=new HashMap();
				String url=node.elementText("url");
				String title=node.elementText("title");
				String keywords=node.elementText("keywords");
				String description=node.elementText("description");
				String text=node.elementText("page-desc-text");
				itemMap.put("title", title);
				itemMap.put("keywords", keywords);
				itemMap.put("description", description);
				itemMap.put("text", text);
				seoMap.put(url, itemMap);
			}
			seoRuleCache=seoMap;
		}catch(DocumentException e){
			log.error(this.getClass().getName()+".cacheSeoRuleMap()"+":"+e);
		}
	}
}
